package pl.extremme.robocode.utils;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author XyC
 */
public class LimitedQueue<E> implements Queue<E> {

    private LinkedList <E> m_collection;
    private int m_size;

    public LimitedQueue(int p_size) {
        if(p_size <= 0) {
            throw new IllegalArgumentException("Size must be greater then zero");
        }
        this.m_collection = new LinkedList<E>();
        this.m_size = p_size;
    }

    @Override
    public boolean add(E e) {
        if(this.m_collection.size() == this.m_size) {
            this.m_collection.removeLast();
        }
        this.m_collection.add(0, e);
        return true;
    }

    @Override
    public boolean offer(E e) {
        if(this.m_collection.size() == this.m_size) {
            return false;
        }
        this.m_collection.add(0, e);
        return true;
    }

    @Override
    public E remove() {
        E first = this.m_collection.getFirst();
        this.m_collection.removeFirst();
        return first;
    }

    @Override
    public E poll() {
        if(this.m_collection.size() > 0) {
            return this.remove();
        } else {
            return null;
        }
    }

    @Override
    public E element() {
        return this.m_collection.getFirst();
    }

    @Override
    public E peek() {
        return this.m_collection.getFirst();
    }

    @Override
    public int size() {
        return this.m_collection.size();
    }

    public int capacity() {
        return this.m_size;
    }

    @Override
    public boolean isEmpty() {
        return this.m_collection.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return this.m_collection.contains(o);
    }

    @Override
    public Iterator<E> iterator() {
        return this.m_collection.iterator();
    }

    @Override
    public Object[] toArray() {
        return this.m_collection.toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return this.m_collection.toArray(a);
    }

    @Override
    public boolean remove(Object o) {
        return this.m_collection.remove(o);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        throw new UnsupportedOperationException("Operation not supported");
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        throw new UnsupportedOperationException("Operation not supported");
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        throw new UnsupportedOperationException("Operation not supported");
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        throw new UnsupportedOperationException("Operation not supported");
    }

    @Override
    public void clear() {
        this.m_collection.clear();
    }

}
